const express = require('express');
const { body } = require('express-validator');
const authController = require('../controllers/authController');
const { authenticate } = require('../middleware/auth');
const { validate } = require('../middleware/validation');

const router = express.Router();

// 注册验证规则
const registerValidation = [
    body('username')
        .isLength({ min: 3, max: 50 })
        .withMessage('用户名长度必须在3-50个字符之间')
        .matches(/^[a-zA-Z0-9_]+$/)
        .withMessage('用户名只能包含字母、数字和下划线'),
    body('email')
        .isEmail()
        .withMessage('请输入有效的邮箱地址')
        .normalizeEmail(),
    body('password')
        .isLength({ min: 6 })
        .withMessage('密码长度至少6位')
        .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
        .withMessage('密码必须包含大小写字母和数字'),
    body('firstName')
        .notEmpty()
        .withMessage('姓氏不能为空')
        .isLength({ max: 50 })
        .withMessage('姓氏长度不能超过50个字符'),
    body('lastName')
        .notEmpty()
        .withMessage('名字不能为空')
        .isLength({ max: 50 })
        .withMessage('名字长度不能超过50个字符'),
    body('phone')
        .optional()
        .matches(/^[0-9\-\+\s\(\)]+$/)
        .withMessage('请输入有效的电话号码')
];

// 登录验证规则
const loginValidation = [
    body('email')
        .isEmail()
        .withMessage('请输入有效的邮箱地址')
        .normalizeEmail(),
    body('password')
        .notEmpty()
        .withMessage('密码不能为空')
];

// 修改密码验证规则
const changePasswordValidation = [
    body('currentPassword')
        .notEmpty()
        .withMessage('当前密码不能为空'),
    body('newPassword')
        .isLength({ min: 6 })
        .withMessage('新密码长度至少6位')
        .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
        .withMessage('新密码必须包含大小写字母和数字')
];

// 路由定义
router.post('/register', registerValidation, validate, authController.register);
router.post('/login', loginValidation, validate, authController.login);
router.get('/me', authenticate, authController.getCurrentUser);
router.put('/profile', authenticate, authController.updateProfile);
router.put('/change-password', authenticate, changePasswordValidation, validate, authController.changePassword);

module.exports = router;